package com.baizhi.utils.guava;

import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class GuavaTest {

    /**
     * Joiner：将集合(或数组/可变参数)通过指定的分隔符连接成字符串
     * Splitter：通过指定的分隔符把字符串转为集合
     */
    @Test
    public void test1() {
        List<String> list = Arrays.asList("a", "b", "c", null);
        Joiner joiner = Joiner.on(",")
//                .skipNulls()    // 忽略null
                .useForNull("NULL");
        System.out.println(joiner.join(list));

        // JDK1.8中的实现
        System.out.println(list.stream().filter(StringUtils::isNotBlank)
                .collect(Collectors.joining(",")));
    }

    @Test
    public void test2() {
        String str = "a,b,  ,c,d";
        // 指定字符串的分隔符
        Splitter splitter = Splitter.on(",")
                .omitEmptyStrings()    // 过滤掉空的字符串
                .trimResults();     // 去除每个元素的前后空格
        Iterable<String> iterable = splitter.split(str);
        System.out.println(iterable);

        // split转为List
        System.out.println(splitter.splitToList(str));
        // split转为Stream
        splitter.splitToStream(str);
    }

    /**
     * 下划线和驼峰互转
     */
    @Test
    public void test3() {
        // 下划线转驼峰
        String str = "student_name";
        // studentName
        System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, str));
        // StudentName
        System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, str));

        // 驼峰转下划线
        str = "studentName";
        // student_name
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str));
    }

    /**
     * Lists的用法，另有Sets、Maps
     */
    @Test
    public void test4() {
        // 提供集合的快速创建方式
        ArrayList<String> list = Lists.newArrayList("a", "b", "c", "d", "e", "f", "g");
        System.out.println(list);

        // 把list分成小的集合，小的集合大小是size
        List<List<String>> partition = Lists.partition(list, 3);
        partition.forEach(System.out::println);
    }

    /**
     * Ints的用法，另有Longs、Floats ...
     */
    @Test
    public void test5() {
        List<Integer> integers = Ints.asList(1, 2, 3);
        System.out.println(integers);
    }
}
